package com.blork.sowidget;

import static android.provider.BaseColumns._ID;
import android.app.AlarmManager;
import android.app.ListActivity;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;



public class QuestionList extends ListActivity {
	
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
        setContentView(R.layout.questions);
        
        this.startService(new Intent(this, SoService.class));
        
        Intent intent = new Intent(this, Widget.class);
        PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0); 
               
        long firstTime = SystemClock.elapsedRealtime();
         
        AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
        am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME,
                        firstTime, AlarmManager.INTERVAL_HOUR, sender);  
         
        
        ListView lv = getListView();
        
		lv.setOnItemClickListener(new OnItemClickListener() {
		    public void onItemClick(AdapterView<?> parent, View view,
		        int position, long id) {
		    	onClick(position, ((TextView) view.findViewById(R.id.id)).getText());

		    }

			private void onClick(int position, CharSequence qID) {
				Intent viewIntent = new Intent("android.intent.action.VIEW", Uri.parse("http://stackoverflow.com/questions/"+qID));  
				startActivity(viewIntent); 
			}
		});
        
        QuestionData qs = new QuestionData(this);
	    SQLiteDatabase db = qs.getReadableDatabase();
		Cursor questionCursor = db.query("questions", new String[] {_ID, "q_id, title, tags, votes, answer_count, user_name"}, 
	                null, null, null, null, null);
		
		startManagingCursor(questionCursor);
		
        int[] displayViews = new int[] { R.id.id, R.id.title, R.id.tags, R.id.votes, R.id.answers, R.id.user };

        String[] displayFields = new String[] { "q_id", "title", "tags", "votes", "answer_count", "user_name"}; 
        
        setListAdapter(new SimpleCursorAdapter(this, 
                       R.layout.question_list_item, questionCursor, 
                       displayFields, displayViews));
       
    }
}

